package com.fighthouse.service;

import java.util.List;
import java.util.TreeMap;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import com.fighthouse.entity.Atleta;
import com.fighthouse.entity.FotoAtleta;


public class AtletaService {
	private static final String PERSISTENCE_UNIT = "fight_site";
	private static Logger logger = Logger.getLogger(Atleta.class);
	
	@SuppressWarnings("unchecked")
	public List<Atleta> getList(){
		logger.debug("** Chamada aos atletas **");
		logger.debug("** Abrindo a conexão **");
		EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
		EntityManager em = entityManagerFactory.createEntityManager();
		
		Query query = (Query) em.createQuery("select atl from Atleta atl");
		List<Atleta> itens = (List<Atleta>) query.getResultList();
		
		for(Atleta item:itens){
			if(item.getFotos() != null){
				TreeMap<FotoAtleta,Integer> ordenada = new TreeMap();
				for(FotoAtleta itemSub:item.getFotos())ordenada.put(itemSub, itemSub.getId());
				item.setFotos(ordenada.keySet());
			}
		}
		
		logger.debug("** Fechando a conexão **");
		em.close();
		entityManagerFactory.close();
		return itens;
	}
	public Atleta update(Atleta item){
		logger.debug("** update atleta **");
		logger.debug("** Abrindo a conexão **");
		EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
		EntityManager em = entityManagerFactory.createEntityManager();

		EntityTransaction tx = em.getTransaction();
		
		tx.begin();
		
		try{
			item = em.merge(item);
			tx.commit();
		}catch(Exception e){
			tx.rollback();
			System.out.println(e.getMessage());
		}
		
		logger.debug("** Fechando a conexão **");
		em.close();
		entityManagerFactory.close();
		
		return item;
	}
	public int delet(List<Atleta> itens){
		logger.debug("** delete atleta **");
		logger.debug("** Abrindo a conexão **");
		EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
		EntityManager em = entityManagerFactory.createEntityManager();

		EntityTransaction tx = em.getTransaction();
		
		tx.begin();
		int i = 0;
		try{
			for(Atleta item:itens){
				em.remove(em.merge(item));
				i++;
			}
			tx.commit();
		}catch(Exception e){
			tx.rollback();
			System.out.println(e.getMessage());
		}
		
		logger.debug("** Fechando a conexão **");
		em.close();
		entityManagerFactory.close();
		
		return i;
	}
}
